import { Box } from '@mui/material';
import { useEffect, useState } from 'react';
import { Label, UnitSelect, ValueInput } from '.';
import { IBaseProps } from './types';
export type FormType = { Unit?: string; Value: number | boolean };
interface IProps extends IBaseProps<FormType> {
  type: 'double' | 'int' | 'boolean';
  label?: string;
  units: unknown;
}
export default function ValueField({
  type,
  value: initValue,
  label,
  units,
  disabled,
  onChange: onInputChange,
}: IProps) {
  const [value, setValue] = useState<number | boolean>();
  const [unit, setUnit] = useState<string>();
  useEffect(() => {
    setValue(initValue.Value);
    setUnit(initValue.Unit);
  }, [initValue]);
  return (
    <Box sx={{ display: 'flex', alignItems: 'center', mt: '4px' }}>
      <Box sx={{ width: units ? '50%' : '60%' }}>
        <Label label={label} />
      </Box>
      <Box
        sx={{
          width: units ? '50%' : '40%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'end',
        }}>
        <Box>
          <ValueInput
            type={type}
            value={value}
            disabled={disabled}
            onChange={(value) => {
              setValue(value);
              onInputChange?.({ Unit: unit, Value: value });
            }}
          />
        </Box>
        {units !== undefined && (
          <Box sx={{ ml: 1 }}>
            <UnitSelect
              units={units}
              value={unit}
              disabled={disabled}
              onChange={(unit) => {
                setUnit(unit);
                onInputChange?.({ Unit: unit, Value: value });
              }}
            />
          </Box>
        )}
      </Box>
    </Box>
  );
}
